package com.apollow.oschina.base;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Dragon on 2017/1/14.
 */

public class BaseActivityVPAdapter extends FragmentStatePagerAdapter {
    private List<Class<? extends BaseFragment>> pagers = new ArrayList<>();
    private List<String> titles = new ArrayList<>();
    private List<Bundle> bundles = new ArrayList<>();
    private Context mContext;

    public BaseActivityVPAdapter(FragmentManager fm, ViewPager viewpager, TabLayout tabLayout) {
        super(fm);
        //将数据适配器设置给ViewPager
        viewpager.setAdapter(this);
        //Tablayout要和ViewPager要绑定/关联
        tabLayout.setupWithViewPager(viewpager);
        mContext = viewpager.getContext();
    }

    public void addFragments(Class<? extends BaseFragment> clazz) {
        pagers.add(clazz);
        notifyDataSetChanged();
    }

    public void addFragments(List<Class<? extends BaseFragment>> clazzs) {
        pagers.addAll(clazzs);
        notifyDataSetChanged();
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = Fragment.instantiate(mContext, pagers.get(position).getName(), bundles.get(position));
        return fragment;
    }

    @Override
    public int getCount() {
        return pagers.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }

    public void addTab(String title, Class<? extends BaseFragment> clazz, Bundle bundle) {
        titles.add(title);
        addFragments(clazz);
        bundles.add(bundle);
    }
}
